﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using VideoNetApplication.Common.CacheManager;
using VideoNetApplication.Common.Dao;
using VideoNetApplication.Common.Extension;
using VideoNetApplication.Common.Helper;
using VideoNetApplication.Common.Web;
using System.Configuration;

namespace VideoNetApplication.Common.Service
{
   public class StudentService
    {
         public HttpContext Context { get; private set; }
        public string PostData { get; set; }

        public string StrValue { get; set; }
        StudentDao dao = new StudentDao();
         public StudentService(HttpContext context)
        {
            Context = context;

            if (Context.Request.Form["strValue"] != null)
                StrValue = Context.Request.Form["strValue"];
            if (Context.Request.Form["PostData"] != null)
                PostData = Context.Request.Form["PostData"];
        }

         public StudentService()
         {
         }

       /// <summary>
        /// 判断用户名是否已经存在
        /// </summary>
        /// <returns></returns>
        public string CheckUserExit()
        {

            return dao.IfNameExist(StrValue).ToString();

        }

        /// <summary>
        /// 用户异步登录
        /// </summary>
        /// <returns></returns>
        public string UserLogin() {
            string rtnMessage;
            int SchoolId = 1;

            if (ConfigurationManager.AppSettings["IsConfig"] == "1")
            {

                if (HttpContext.Current.Request["SchoolId"] != null && StringUtils.IsNumeric(HttpContext.Current.Request["SchoolId"]))
                {
                    SchoolId = Convert.ToInt32(HttpContext.Current.Request["SchoolId"]);
                }
            }
            else
            {

                SchoolId = Convert.ToInt32(ConfigurationManager.AppSettings["SchoolID"]);
            }
            V_user user = dao.UserLoginBySchoolID(PostData, StrValue, SchoolId);

            if (user != null)
            {
                if ((bool)user.IsAvailable)
                {
                    dao.AddUserLog(user);
                    FormsAuthentication.SetAuthCookie(MembershipService.GenerateName(user.ID, SchoolId), false);
                    MembershipService.FlushUser(user.ID, Convert.ToInt32(user.SchoolID));
                    CourseService service = new CourseService();
                    DataSet ds = service.GetUserCourseList(user.ID, Convert.ToInt32(user.SchoolID), "", "");
                    //将学员数据放入缓存中
                    CommonCacheManager.AddCacheData<DataSet>("UserCourse" + user.ID, ds, 60);
                    rtnMessage = "Success";
                }
                else
                {
                    rtnMessage = "用户已被禁用，请联系管理员！！";
                }
            }
            else {

                rtnMessage = "登录名或密码错误！";
            }
            return rtnMessage;
          
        
        }
        public  string  LoginOut()
        {

            FormsAuthentication.SignOut();
            CommonCacheManager.FlushCache();
            return "Success";
        }
       /// <summary>
       /// 判断用户的用户名和密码
       /// </summary>
       /// <returns></returns>
       public  string  CheckUserPass()
       { 
          V_user vUser=dao.UserLoginBySchoolID(MembershipService.GetUser().VU_loginname, PostData,(int)MembershipService.GetUser().SchoolID);
          if(vUser!=null) {
               return "Success";
           }
           return "False";
       }

       public string  GetComment()
       {
            string courseid = Context.Request["strValue"];
           int pageIndex =Convert.ToInt32(Context.Request["pageIndex"]);
           int pageSize = Convert.ToInt32(Context.Request["pageSize"]);
           StringBuilder sb=new StringBuilder();
           CommentService commentService=new CommentService();
           List<V_VideoComment> vVideoComments = commentService.GetMessageList(Convert.ToInt32(courseid), (pageIndex - 1 )* pageSize,
                                                                               pageSize);
           if(vVideoComments!=null)
           {
               foreach (var item in vVideoComments)
               {
                   sb.AppendFormat("<dl> <dt><strong>{0}</strong><span>发表于{1}</span></dt><dd>{2}</dd></dl>", item.CommentUserName, Convert.ToDateTime(item.CreatedTime).ToString("yyyy-MM-dd"), item.CommentContent);
                   
               }
            
           }
           return sb.ToString();
       }

       /// <summary>
       /// 修改学员信息
       /// </summary>
       /// <returns></returns>
       public  string ModifyUser()
       {
           string newpwd = Context.Request["strValue"];
           var user = PostData.FromJsonTo<V_user>();
   
           if(!string.IsNullOrEmpty(newpwd))
           {
               user.VU_Password = StringUtils.EncryptPassWord(newpwd, StringUtils.PassFormat.MD5);

           
           }
           user.VU_loginname = MembershipService.GetUser().VU_loginname;
           user.SchoolID = MembershipService.GetUser().SchoolID;
         if( dao.AddUser(user)>0)
         {
             
            return  "True";
         }

           return "False";
       }

       public  string  SubmitComment()
       {
           V_VideoComment comment=new V_VideoComment();
           comment.CommentContent = StrValue;
           comment.CommentUserId = MembershipService.GetUser().ID;
           comment.CreatedTime = DateTime.Now;
           comment.CommentUserName = MembershipService.GetUser().VU_realname;
           comment.CourseListId = Convert.ToInt32(PostData);
           var commentService = new CommentService();
           if (commentService.AddComment(comment)>0)
           {
               return "Success";
           }

           return "False";
       }

       //public  string  CoursePreList()
       //{
       //    DateTime courseDate = DateTime.Parse(Context.Request["CourseDate"]);
       //    DateTime startTime = DateTime.Parse(Context.Request["StartTime"]);
       //    DateTime endTime = DateTime.Parse(Context.Request["EndTime"]);
       //    int roomId = int.Parse(Context.Request["RoomId"]);
       //    int currentY = int.Parse(Context.Request["CurrentY"]);
       //    int currentM = int.Parse(Context.Request["CurrentM"]);
       //    int currentMd = int.Parse(Context.Request["CurrentMd"]);
       //    DateTime start = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, startTime.Hour, startTime.Minute, startTime.Second);
       //    DateTime end = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, endTime.Hour, endTime.Minute, endTime.Second);
       //    CourseWeek courseWeek=new CourseWeek();
       //    int maxDay = 0;
       //    int minDay = 0;
       //    return courseWeek.GetCourseWeek(currentY, currentM, currentMd, 1) ;
          

       //}
       //public string CourseNextList()
       //{
       //    DateTime courseDate = DateTime.Parse(Context.Request["CourseDate"]);
       //    DateTime startTime = DateTime.Parse(Context.Request["StartTime"]);
       //    DateTime endTime = DateTime.Parse(Context.Request["EndTime"]);
       //    int roomId = int.Parse(Context.Request["RoomId"]);
       //    int currentY = int.Parse(Context.Request["CurrentY"]);
       //    int currentM = int.Parse(Context.Request["CurrentM"]);
       //    int currentMd =  int.Parse(Context.Request["CurrentMd"]) ;
       //    DateTime start = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, startTime.Hour, startTime.Minute, startTime.Second);
       //    DateTime end = new DateTime(courseDate.Year, courseDate.Month, courseDate.Day, endTime.Hour, endTime.Minute, endTime.Second);
            


       //    CourseWeek courseWeek = new CourseWeek();
       //    int maxDay = 0;
       //    int minDay = 0;


       //    return courseWeek.GetCourseWeek(currentY, currentM, currentMd, 2);


       //}

    



       /// <summary>
        /// 用户密码找回
        /// </summary>
        /// <returns></returns>
        public string FindUserPwd()
        {

            if (HttpContext.Current.Session["CheckCode"] != null)
            {
                if (HttpContext.Current.Session["CheckCode"].ToString() != StrValue)
                    return "ErrorVCode";
            }
            //首先验证用户名和邮箱是否一致
            var user = PostData.FromJsonTo<V_user>();
            if (dao.CheckUnameByEmail(user))
            {
                //发送邮件到用户邮箱
                var eh = new EmailHelper();
                var random = new Random();
                var newPwd = random.Next(0, 999999).ToString();
                if (eh.Send(user.VU_email, "密码找回", "尊敬的学员你好：你的新密码是" + newPwd))
                {
                    //邮件发送成功了 保存用户的新密码
                    user.VU_Password = StringUtils.EncryptPassWord(newPwd, StringUtils.PassFormat.MD5);
                    if (dao.UpdateUserPwd(user) > 0)
                    {
                        return "True";
                    }
                }

            }
            return "False";
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        public string RegistUser()
        {
            var user = PostData.FromJsonTo<V_user>();
            user.create_time = DateTime.Now;
            user.IsAvailable = false;
            user.update_time = DateTime.Now;
            //user.IsBuyingAccount = 1;
            user.VU_Password = StringUtils.EncryptPassWord(PostData, StringUtils.PassFormat.MD5);
            if (dao.AddUser(user) > 0)
            {
                //记录用户登录日志
                dao.AddUserLog(user);
                //将用户登录
                HttpContext.Current.Session["currentUser"] = user;
                return "1";
            }
            return "0";
        }
       public  int AddUserLog(V_user vUser)
       {
           return dao.AddUserLog(vUser);
       }

    }
} 
